import { loginByMobile, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
  	mobile:'',
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
     // 用户名登录
    LoginByMobile({ commit }, userInfo) {
      const mobile = userInfo.mobile.trim()
      return new Promise((resolve, reject) => {
        // console.log(userInfo)
        loginByMobile(mobile, userInfo.password).then(response => {

          // 正式处理登录结果
          // {"Code":291,"Status":1,"Description":"登陆成功","Data":"eyJNZW1iZXJJZCI6MSwiVXNlcm5hbWUiOiIxODg4ODg4ODg4OCIsIkVtYWlsIjoiMTIzNDU2Nzg5QHFxLmNvbSIsIk5pY2tuYW1lIjoiMTg4ODg4ODg4ODgiLCJBdmF0YXIiOiJodHRwczovL3dlYi1iZWl3YW4ub3NzLWNuLWhhbmd6aG91LmFsaXl1bmNzLmNvbS9hcHBpbWcvSGVhZF9JbWcvaW1nXzAzLnBuZyIsIk1vYmlsZSI6IjE4ODg4ODg4ODg4IiwiU2V4IjoxLCJEZXNjcmlwdGlvbiI6IuaJi+acuuWFmiIsIkJpcnRoZGF5IjoiMjAwMC0wMS0wMVQwMDowMDowMCIsIkFkZHJlc3MiOiLmuZbljZfnmoQiLCJTZXNzaW9uSWQiOiJmY2FkZDdlZi0zZjY4LTQ4MTctOGU1Yy01NTgwOGYwZjhiNWQiLCJTdGF0dXMiOjAsIlJvbGVzIjowfQ=="}
          // eyJNZW1iZXJJZCI6MSwiVXNlcm5hbWUiOiIxODg4ODg4ODg4OCIsIkVtYWlsIjoiMTIzNDU2Nzg5QHFxLmNvbSIsIk5pY2tuYW1lIjoiMTg4ODg4ODg4ODgiLCJBdmF0YXIiOiJodHRwczovL3dlYi1iZWl3YW4ub3NzLWNuLWhhbmd6aG91LmFsaXl1bmNzLmNvbS9hcHBpbWcvSGVhZF9JbWcvaW1nXzAzLnBuZyIsIk1vYmlsZSI6IjE4ODg4ODg4ODg4IiwiU2V4IjoxLCJEZXNjcmlwdGlvbiI6IuaJi+acuuWFmiIsIkJpcnRoZGF5IjoiMjAwMC0wMS0wMVQwMDowMDowMCIsIkFkZHJlc3MiOiLmuZbljZfnmoQiLCJTZXNzaW9uSWQiOiJiYjhhMTdmNC00MDRmLTQzYjgtYmJjZC1lOWI4ODU1ZmI2YjYiLCJTdGF0dXMiOjAsIlJvbGVzIjowfQ==
          // {"MemberId":1,"Username":"18888888888","Email":"123456789@qq.com","Nickname":"18888888888","Avatar":"https://web-beiwan.oss-cn-hangzhou.aliyuncs.com/appimg/Head_Img/img_03.png","Mobile":"18888888888","Sex":1,"Description":"手机党","Birthday":"2000-01-01T00:00:00","Address":"湖南的","SessionId":"bb8a17f4-404f-43b8-bbcd-e9b8855fb6b6","Status":0,"Roles":0}


          var data = response.data
          data = data.Data
          var userDataStr = Base64.decode(data)
          var userData = JSON.parse(userDataStr)

          // 在VUEX 中设置登录标签
          commit('SET_TOKEN', userData.SessionId)
          setToken(userData.SessionId)
          // 当然你也可以在这里更新 localStorage
          localStorage.setItem("userinfo",userDataStr)
          localStorage.setItem("sessionid",userData.SessionId)

          resolve()



        }).catch(error => {
          reject(error)
        })
      })
    },

  // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {

        // 直接从localStorage里面设置用户的资料
        var userInfo = JSON.parse(localStorage.getItem('userinfo'))
        console.log('直接从localStorage里面设置用户的资料')
        commit('SET_NAME', userInfo.Nickname)
        commit('SET_AVATAR', userInfo.Avatar)
        commit('SET_INTRODUCTION', userInfo.Description)
        // 这里强制写死了用户的角色，后期请根据需要调整
        var roles = ['admin']
        commit('SET_ROLES', roles)
        resolve(roles)
        // getUserInfo(state.token).then(response => {
        //   // 由于mockjs 不支持自定义状态码只能这样hack
        //   if (!response.data) {
        //     reject('Verification failed, please login again.')
        //   }
        //   const data = response.data

        //   if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
        //     commit('SET_ROLES', data.roles)
        //   } else {
        //     reject('getInfo: roles must be a non-null array!')
        //   }

        //   commit('SET_NAME', data.name)
        //   commit('SET_AVATAR', data.avatar)
        //   commit('SET_INTRODUCTION', data.introduction)
        //   resolve(response)
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({ commit, dispatch }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          dispatch('GenerateRoutes', data) // 动态修改权限后 重绘侧边菜单
          resolve()
        })
      })
    }
  }
}

export default user
